/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.views.impl;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.biz.PagingCmd;
import cn.easyplatform.studio.cmd.biz.QueryCmd;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.BizQueryResultVo;
import cn.easyplatform.studio.vos.BizQueryVo;
import cn.easyplatform.studio.web.editors.EditorCallback;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.OpenEvent;
import org.zkoss.zul.*;
import org.zkoss.zul.event.PagingEvent;
import org.zkoss.zul.event.ZulEvents;

import java.util.Iterator;
import java.util.List;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
class QueryView extends AbstractView<String> {

	private Listbox grid;

	private BizQueryVo vo;

	private Paging paging;

	private Bandbox searchbox;

	private String[] labels;

	private boolean isMultiple;

	/**
	 * @param cb
	 */
	protected QueryView(EditorCallback<String> cb, BizQueryVo vo,
			boolean isMultiple, Component component, String... labels) {
		super(cb);
		this.vo = vo;
		this.isMultiple = isMultiple;
		this.labels = labels;
	}

	@Override
	protected void createHeader(Component parent) {
		// 搜索栏
		North searchbar = new North();
		searchbar.setBorder("none");
		searchbar.setSize("28px");
		searchbar.setHflex("1");
		Div bar = new Div();
		bar.setHflex("1");
		Label label = new Label(Labels.getLabel("entity.search.key") + ":");
		label.setParent(bar);
		searchbox = new Bandbox();
		searchbox.setId("queryView_bandbox_search");
		searchbox.setPlaceholder(Labels.getLabel("message.search",
				new String[] { vo.getSearchField() }));
		searchbox.addEventListener(Events.ON_OK, this);
		searchbox.addEventListener(Events.ON_OPEN, this);
		searchbox.setParent(bar);
		if (isMultiple) {
			Button btn = new Button(Labels.getLabel("button.ok"));
			btn.setId("queryView_button_ok");
			btn.setSclass("pull-right");
			btn.setIconSclass("z-icon-check");
			btn.addEventListener(Events.ON_CLICK, this);
			btn.setParent(bar);
		}
		bar.setParent(searchbar);
		searchbar.setParent(parent);
	}

	@Override
	protected void createContent(Component parent) {
		grid = new Listbox();
		grid.setId("queryView_listbox_result");
		grid.setHflex("1");
		grid.setVflex("1");
		grid.setSizedByContent(true);
		grid.setSpan(true);
		if (isMultiple) {
			grid.setMultiple(true);
			grid.setCheckmark(true);
		}
		Listhead columns = new Listhead();
		columns.setSizable(true);
		for (String label : labels)
			columns.appendChild(new Listheader(label));
		columns.setParent(grid);
		grid.setParent(parent);
	}

	private void redraw(List<Object[]> data) {
		for (Object[] vo : data) {
			Listitem row = new Listitem();
			row.setValue(vo);
			for (Object v : vo)
				row.appendChild(new Listcell(v == null ? "" : v.toString()));
			row.setParent(grid);
			if (!isMultiple)
				row.addEventListener(Events.ON_DOUBLE_CLICK, this);
		}
	}

	@Override
	protected void createFooter(Component parent) {
		paging = new Paging();
		paging.setPageSize(20);
		paging.setDetailed(true);
		paging.addEventListener(ZulEvents.ON_PAGING, this);
		South south = new South();
		south.setBorder("none");
		south.setHflex("1");
		south.setSize("30px");
		south.appendChild(paging);
		south.setParent(parent);
		BizQueryResultVo result = StudioApp.execute(grid, new QueryCmd(vo,
				paging.getPageSize()));
		paging.setTotalSize(result.getTotalSize());
		redraw(result.getResult().getData());
	}

	@Override
	public void onEvent(Event event) throws Exception {
		if (event.getName().equals(ZulEvents.ON_PAGING)) {
			PagingEvent pe = (PagingEvent) event;
			int pageNo = pe.getActivePage() + 1;
			if (Strings.isBlank(searchbox.getValue()))
				vo.setSearchValue(null);
			else
				vo.setSearchValue(searchbox.getValue());
			List<Object[]> data = StudioApp.execute(paging, new PagingCmd(vo,
					paging.getPageSize(), pageNo));
			grid.getItems().clear();
			redraw(data);
		} else if (event.getTarget() == searchbox) {
			String val = null;
			if (event instanceof OpenEvent) {
				OpenEvent evt = (OpenEvent) event;
				val = (String) evt.getValue();
			} else
				val = searchbox.getValue();
			if (Strings.isBlank(val))
				vo.setSearchValue(null);
			else
				vo.setSearchValue(val.trim());
			BizQueryResultVo result = StudioApp.execute(grid, new QueryCmd(vo,
					paging.getPageSize()));
			paging.setTotalSize(result.getTotalSize());
			grid.getItems().clear();
			redraw(result.getResult().getData());
		} else {
			if (isMultiple) {
				if (grid.getSelectedIndex() < 0) {
					WebUtils.showError(Labels
							.getLabel("editor.select", new Object[] { Labels
									.getLabel("editor.bpm.record") }));
				} else {
					Iterator<Listitem> itr = grid.getSelectedItems().iterator();
					StringBuilder sb = new StringBuilder();
					while (itr.hasNext()) {
						Listitem li = itr.next();
						Object[] data = li.getValue();
						sb.append(data[0] == null ? "" : data[0].toString());
						if (itr.hasNext())
							sb.append(",");
					}
					cb.setValue(sb.toString());
					grid.getRoot().detach();
					onCloseClick(win);
				}
			} else {
				Listitem row = (Listitem) event.getTarget();
				Object[] data = row.getValue();
				cb.setValue(data[0] == null ? "" : data[0].toString());
				grid.getRoot().detach();
				onCloseClick(win);
			}
		}
	}

}
